﻿--[[
	Copyright (c) 2012 Eyal Shilony

	Permission is hereby granted, free of charge, to any person obtaining
	a copy of this software and associated documentation files (the
	"Software"), to deal in the Software without restriction, including
	without limitation the rights to use, copy, modify, merge, publish,
	distribute, sublicense, and/or sell copies of the Software, and to
	permit persons to whom the Software is furnished to do so, subject to
	the following conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
	MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN 
	
	NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
	LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
	OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
	WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

	-- Provides a friendlier methodology to add options to the Blizzard Interface Options panel using AceConfig.
]]

local addonName, addon = ...

local config = LibStub("AceConfig-3.0")
local dialog = LibStub("AceConfigDialog-3.0")

local function fixOptionsTable(source, argsfix)
	local dest = { }
	for k, v in pairs(source) do
		if type(v) ~= "table" then
			if tonumber(k) then 
				tinsert(dest, k, v)
			else
				dest[k] = v
			end
		else
			if tonumber(k) and argsfix then
				local key = tostring(k);
				dest[key] = fixOptionsTable(v)
				dest[key].order = k
			elseif k == "args" then
				dest[k] = fixOptionsTable(v, true)
			else
				dest[k] = fixOptionsTable(v)
			end
		end
	end
	return dest
end

local parentName
function addon:RegisterOptions(table, legacyOptionsFormat)
	if not table or not type(table) == "table"  then
		error("Argument 'table' is not a table.")
	end
	if not table.name then
		error("Cannot find a 'name' entry in the provided table.")
	end
	if not legacyOptionsFormat then
		table = fixOptionsTable(table)
	end
	local name = addonName .. "_" .. table.name
	config:RegisterOptionsTable(name, table)
	if not parentName then
		parentName = table.name
		dialog:AddToBlizOptions(name, table.name)
	else
		dialog:AddToBlizOptions(name, table.name, parentName)
	end
end